<?php

namespace App\Recharge\Api;

use App\Jobs\SynChronousOrder;
use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use App\Recharge\Bean\RequestResultBean;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class Shijuanbao extends AbstractApi
{
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key): string
    {
        $sign = "";
        ksort($array);
        foreach ($array as $key => $value) {
            if (!$value && ($value != 0)) {
                continue;
            }
            $sign .= $key . "=" . $value . "&";
        }
        $sign  = substr($sign, 0, -1);
        return md5($sign.$secret_key);
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'mchId' => $bean->getSupplierNum(),
            'chargeAccount' => $bean->getAccount(),
            'productCode' => $bean->getGoodsId(), //商品编码
            'buyCount' => ($bean->getRechargeNum() * $bean->getStartCharging()),
            'customerOrderId' => $bean->getOrderNo(), //订单号
            'notifyUrl' => $bean->getNotifyUrl(), //异步回调地址
            'timestamp' =>round(microtime(true) * 1000)
        ];
        ksort($array);
        $array['sign'] = $this->sign($array ,$bean->getSecretKey());
        return $array;
    }

    /**
     * @param InterfaceConfiguration $config
     * @param BasicInformation $dataBean
     * @param RequestResultBean $bean
     * @return RequestResultBean
     */
    public function synchronous_processing(InterfaceConfiguration $config, BasicInformation $dataBean, RequestResultBean $bean): RequestResultBean
    {
        // 第三方接口返回的错误信息
        $errMessage = "";
        // 请求返回信息转数组
        $resp = json2array($bean->getResponse());
        $bean->setFormatResponse($resp);
        // 解析json 解析失败的话 就默认成功
        $result = data_get($resp, 'code') == 1;
        if (!$result) {
            $errMessage = data_get($resp, 'msg', $config->title . '下单失败');
        }
        // 判断并返回
        return $bean->setResult($result)
            ->setErrorMessage($errMessage)
            ->setApiSynchronousEndProcessing(function() use ($result, $resp, $dataBean) {
                $data = [
                    'code'=>$resp['code'],
                    'order_sn'=>$dataBean->getOrderNo(),
                    'msg'=>$resp['message'],
                ];
                SynChronousOrder::dispatch($dataBean->getNotifyUrl(),$data)->delay(Carbon::now())->onConnection('redis')->onQueue('sync_order');
            });
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('code', '');
        $order_sn = $request->input('order_sn', '');
        return $this
            ->apiNotifyData($order_sn, $status)
            ->setExecute(in_array($status, ['1', '0']))
            ->setRechargeSuccess($status == '1')
            ->setRechargeErrorMessage($request->input('msg', ''));
    }

}
